package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.LoginDto;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.BCrypt;
import com.heima.utils.common.Base64Utils;
import com.heima.utils.common.JwtUtils;
import com.heima.utils.common.RsaUtils;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {


    @Value("${leadnews.jwt.expire}")
    private Integer expire;

    @Value("${leadnews.jwt.privateKeyPath}")
    private String privateKeyPath;

    @Override
    public ResponseResult<Map<String, Object>> login(WmLoginDto dto) {
        String name = dto.getName();
        String password = dto.getPassword();
        //数据校验
        if(StringUtils.isEmpty(name) || StringUtils.isEmpty(password)){
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //判断参数

        QueryWrapper<WmUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name); //.select("id","password") 指定查询字段
        WmUser wmUser = getOne(queryWrapper);

        //查询用户名存在
        if (wmUser == null) {
            throw new LeadNewsException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        if (!BCrypt.checkpw(password, wmUser.getPassword())) {
            throw new LeadNewsException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        wmUser.setPassword(null);

        //读取私钥文件
        try {
            PrivateKey privateKey = RsaUtils.getPrivateKey(privateKeyPath);
            String token = JwtUtils.generateTokenExpireInMinutes(wmUser, privateKey, expire);

            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("token",token);
            resultMap.put("user",wmUser);

            return ResponseResult.okResult(resultMap);
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }
}
